package com.wk.net.connector.mockServer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.wk.net.connector.AcceptedClient;
import com.wk.net.connector.SocketServer;



/**
 * 测试类：模拟的TCP服务器，打印收到的所有内容
 * 
 * @author Bai Yu
 *
 */
public class MockTcpServer {
	public static void main(String[] args) {
		final int PORT = 8086;

		SocketServer server = new SocketServer(PORT);
		try {
			server.listen();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		while (true) {
			AcceptedClient client;
			try {
				client = server.accept();
			} catch (IOException e) {
				server.close();
				e.printStackTrace();
				break;
			}

			System.out.println("来自：" + client.getDisplayName());
			try {
				client.establish();
			} catch (IOException e) {
				e.printStackTrace();
				continue;
			}
			receiveFrom(client);
		}
	}

	private static void receiveFrom(AcceptedClient client) {
		ByteArrayOutputStream content = new ByteArrayOutputStream();
		try {
			while (true) {
				int b = client.getCallStream().read();
				if (b == -1) {
					break;
				}
				content.write(b);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			client.close();
			System.out.println(new String(content.toByteArray()));
		}
	}
}
